package com.wzbc.video.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzbc.video.entity.User;
import com.wzbc.video.mapper.UserMapper;
import com.wzbc.video.req.UserSearchReq;
import com.wzbc.video.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    public UserMapper userMapper;

    @Override
    public IPage<User> myList(UserSearchReq req) {
        return userMapper.selectPage(new Page<>(req.getPageCurrent(), req.getPageSize()),new LambdaQueryWrapper<User>()
                .like(req.getId() != null && !req.getId().equals(0L), User::getUserId, req.getId())
                .like(req.getUsername()!=null && !req.getUsername().isEmpty(),User::getUsername,req.getUsername())
                .like(req.getNickname()!=null && !req.getNickname().isEmpty(),User::getNickname,req.getNickname()));
    }

    @Override
    public Integer validateUsername(String username) {
        return userMapper.selectList(
                new LambdaQueryWrapper<User>()
                        .select(User::getUsername)
                        .eq(User::getUsername, username)
        ).size();
    }

    @Override
    public Long validateLogin(String username, String password) {
        List<User> users = userMapper.selectList(
                new LambdaQueryWrapper<User>()
                        .eq(User::getUsername, username)
                        .eq(User::getPassword, password)
        );
        if (users.size() == 0) {
            return 0L;
        }
        return users.get(0).getUserId();
    }

    @Override
    public Integer insert(User user) {
        if (validateUsername(user.getUsername()) == 0) {
            return userMapper.insert(user);
        }
        return null;
    }

    @Override
    public Integer update(User user) {
        return userMapper.updateById(user);
    }

    @Override
    public User getInfo(Long id) {
        return null;
    }

    @Override
    public Integer deleteById(Long id) {
        return this.baseMapper.deleteById(id);
    }
}
